﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using NHibernate.Cfg;

namespace ZenMoney.Core.DataAccess.Config
{
	public class ConfigLoader
	{
		private const string ConfigFile = "config.bin";

		public static Configuration LoadFromFile()
		{
			if (!ConfigIsValid())
				return null;

			try
			{
				using (var file = File.OpenRead(ConfigFile))
				{
					var formatter = new BinaryFormatter();
					return formatter.Deserialize(file) as Configuration;
				}
			}
			catch
			{
				return null;				
			}
		}

		private static bool ConfigIsValid()
		{
			var fileInfo = new FileInfo(ConfigFile);

			if (!fileInfo.Exists)
				return false;

			var asm = Assembly.GetExecutingAssembly();
			var asmInfo = new FileInfo(asm.Location);

			if (asmInfo.LastWriteTime > fileInfo.LastWriteTime)
				return false;

			var appDomain = AppDomain.CurrentDomain;
			var appConfigPath = appDomain.SetupInformation.ConfigurationFile;
			var appConfigInfo = new FileInfo(appConfigPath);

			if (appConfigInfo.LastWriteTime > fileInfo.LastWriteTime)
				return false;

			return true;
		}

		public static void SaveToFile(Configuration config)
		{
			using (var file = File.Open(ConfigFile, FileMode.Create))
			{
				var formatter = new BinaryFormatter();
				formatter.Serialize(file, config);
			}
		}
	}
}
